package algorithm.leetcode.medium;

/*
给定一个机票的字符串二维数组 [from, to]，子数组中的两个成员分别表示飞机出发和降落的机场地点，
对该行程进行重新规划排序。所有这些机票都属于一个从 JFK（肯尼迪国际机场）出发的先生，
所以该行程必须从 JFK 开始。

 */

import java.util.*;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2021/1/4
 */
public class Question332 {

    public static void main(String[] args) {

    }

    public List<String> findItinerary(List<List<String>> tickets) {
        List<String> ans = new LinkedList<>();
        if (tickets == null || tickets.size() == 0) {
            return ans;
        }
        Map<String, PriorityQueue<String>> graph = new HashMap<>(16);
        for (List<String> ticket : tickets) {
            PriorityQueue<String> nbr = graph.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>());
            nbr.add(ticket.get(1));
        }
        visit(graph, "JFK", ans);
        return ans;
    }

    private void visit(Map<String, PriorityQueue<String>> graph, String src, List<String> ans) {
        Stack<String> stack = new Stack<>();
        stack.push(src);
        while (!stack.isEmpty()) {
            PriorityQueue<String> nbr;
            while ((nbr = graph.get(stack.peek())) != null && nbr.size() > 0) {
                stack.push(nbr.poll());
            }
            ans.add(0, stack.pop());
        }
    }
}
